<template>
  <div class="p-10">
    <vxe-form size="small" :data="queryForm" v-show="querydfFields.length>0" @submit="dfQuery">
      <vxe-form-item v-for="(item,index) in querydfFields" :title="item.fieldTitle" :field="item.fieldName" :key="index" :item-render="{}">
        <template #default="{ data }">
          <div v-if="item.fieldAreaName==='between'">
            <Between :type="item.dataTypeID===4?'date':'text'" v-model="data[item.fieldName]"></Between>
          </div>
          <div v-else>
            <vxe-input   v-model="data[item.fieldName]" placeholder="请输入条件值"></vxe-input>
          </div>
        </template>
      </vxe-form-item>

      <vxe-form-item>
        <template #default>
          <vxe-button size="small" v-if="querydfFields.length>0" type="submit" status="primary">查询</vxe-button>
          <vxe-button size="small" v-if="querydfFields.length>0" type="reset">重置</vxe-button>

        </template>
      </vxe-form-item>
    </vxe-form>
    <vxe-grid ref='xGrid' v-bind="gridOptions">
      <template #defaultForm="{ row ,column}">
        {{row[column.params.column.fieldName]}}
      </template>
      <template #editForm="{ row ,column}">
        <div v-if="column.params.column.dataTypeID===1">
          <vxe-input v-model="row[column.params.column.fieldName]" v-show="column.params.column.componentID===0" :readonly="column.params.column.editable===0"
                     @blur="ValueChange(row,Fields[column.params.column.tableName],column.params.column.fieldName,MainTable.tableName)"></vxe-input>
          <el-input v-if="column.params.column.componentID>0 && [3,6].includes(column.params.column.componentType)" :value="getextend(row,column.params.column)"
                    v-show="column.params.column.componentID>0" placeholder="请点击选择..." readonly
                    @blur="ValueChange(row,Fields[MainTable.tableName],column.params.column.fieldName,MainTable.tableName)">
            <template #append>
              <el-button :disabled="column.params.column.editable===0" @click="showSource({item:column.params.column ,value:row[column.params.column.fieldName],target:row,ref:MainTable.tableName})"
                         size="default" :icon="Plus"/>
            </template>
          </el-input>
          <vxe-select v-if="column.params.column.componentID>0 && column.params.column.componentType===1" :readonly="column.params.column.editable===0"
                      v-model="row[column.params.column.fieldName]" placeholder="下拉框" clearable
                      @blur="ValueChange(row,Fields[MainTable.tableName],column.params.column.fieldName,MainTable.tableName)" transfer>
            <vxe-option v-for="(it,index) in Combo[column.params.column.fieldName]" :value="it.value" :label="it.label"
                        :key="index"></vxe-option>
          </vxe-select>
          <vxe-input v-if="column.params.column.componentID>0 && column.params.column.componentType===5" v-model="row[column.params.column.fieldName]"
                     :readonly="column.params.column.editable===0" placeholder="自动取得编号"
                     @suffix-click="getAutoCode( Fields[MainTable.tableName],row,column.params.column.fieldName,MainTable.tableName)">
            <template #suffix><i class="el-icon-refresh-right"></i></template>
          </vxe-input>
        </div>
        <vxe-input v-if="column.params.column.dataTypeID===2" v-model="row[column.params.column.fieldName]" placeholder="请输入..."
                   :readonly="column.params.column.editable===0" type="integer"
                   @blur="ValueChange(row,Fields[MainTable.tableName],column.params.column.fieldName,MainTable.tableName)"></vxe-input>
        <vxe-input v-if="column.params.column.dataTypeID===3" v-model="row[column.params.column.fieldName]" placeholder="请输入..." autoselect
                   :readonly="column.params.column.editable===0" type="float" :digits="column.params.column.fieldPrecision"
                   @blur="ValueChange(row,Fields[MainTable.tableName],column.params.column.fieldName,MainTable.tableName)"></vxe-input>
        <vxe-input v-if="column.params.column.dataTypeID===4" v-model="row[column.params.column.fieldName]" placeholder="请输入..."
                   :readonly="column.params.column.editable===0" transfer clearable type="date"
                   @blur="ValueChange(row,Fields[MainTable.tableName],column.params.column.fieldName,MainTable.tableName)"></vxe-input>
        <div v-if="[5,10].includes(column.params.column.dataTypeID)">
          <vxe-input v-model="row[column.params.column.fieldName]" v-show="false"></vxe-input>
          <vxe-input :value="getextend(row,column.params.column)" placeholder="请选择图片" readonly class="my-search"
                     @suffix-click="showFiles({item:column.params.column ,value:row[column.params.column.fieldName],target:row,ref:MainTable.tableName,multiple:false,fileType:'images'})"
                     @blur="ValueChange(row,Fields[MainTable.tableName],column.params.column.fieldName,MainTable.tableName)">
            <template #suffix>
              <el-icon>
                <Plus/>
              </el-icon>
            </template>
          </vxe-input>
        </div>
        <div v-if="column.params.column.dataTypeID===6">
          <vxe-input v-model="row[column.params.column.fieldName]" v-show="false"></vxe-input>
          <el-input size="default" @change="ValueChange(row,Fields[column.params.column.tableName],column.params.column.fieldName,column.params.column.tableName)"
                    placeholder="请选择文件" :readonly="column.params.column.editable===0||statusCode!==0"
                    type="text" :value="getextend(row,column.params.column)">
            <template #append>
              <el-button :disabled="column.params.column.editable===0"
                         @click="showFiles({item:column.params.column ,value:row[column.params.column.fieldName],target:row,ref:MainTable.tableName,multiple:true,fileType:'files'})"
                         size="default" :icon="Plus"/>
            </template>
          </el-input>
        </div>
        <vxe-input v-if="column.params.column.dataTypeID>=7" v-model="row[column.params.column.fieldName]" placeholder="请输入..."
                   :readonly="column.params.column.editable===0" clearable
                   @blur="ValueChange(row,Fields[MainTable.tableName],column.params.column.fieldName,MainTable.tableName)"></vxe-input>
      </template>
      <template #operator="{ row }">
        <template v-if="$refs.xGrid.isEditByRow(row)">
          <vxe-button @click="saveRowEvent(row)">保存</vxe-button>
          <vxe-button @click="cancelRowEvent(row)">取消</vxe-button>
        </template>
        <template v-else>
          <vxe-button @click="editRowEvent(row)">编辑</vxe-button>
<!--          <vxe-button @click="removeRowEvent(row)">删除</vxe-button>-->
        </template>
      </template>
    </vxe-grid>
    <DataGridSelect ref="DGE" :isequipment="isequipment" @submit="getSourceData"></DataGridSelect>

  </div>
</template>

<script>
import {onBeforeMount, reactive, ref, toRefs,} from "vue"
import {useRoute, useRouter} from 'vue-router'
import XEUtils from "xe-utils"
import VXETable from 'vxe-table'
import {listTemplate,getForm,getTemplate,importTemplate,editsForm,delTemplate} from "/@/api/linkoo/form/index"
import Between from '/@/views/views/components/between.vue';
import {ElMessage} from "element-plus";
import {mathAll} from "../../../utils/mathji";
import DataGridSelect from '/@/views/linkoo/components/select.vue'
import {Plus} from '@element-plus/icons-vue'


export default {

  name:'formEditsMain11',
  components: {Between,DataGridSelect},
  setup(props) {
    let router = useRouter()
    let xGrid = ref()
    let DGE = ref()
    let fastSearch  = ref()
    const route = useRoute()
    let state = reactive({
      Fields: {},
      AllData: { StatusCode:0 },
      Template: {},
      MainTable: {},
      selectDataGridTarget: {},
      DetailTables: [],
      combo: {}, rules: {},
      isequipment: true,
      queryFromShow: false,
      queryBuildShow : false,
      ActRules: {},
      queryForm: {},
      querydfFields: [],
      templateCode: '',
      Linker: {},
      gridOptions:{
        border: true,
        showHeaderOverflow: true,
        showOverflow: true,
        keepSource: true,
        id: 'full_edit_1',
        height: 800,
        columnConfig: {
          resizable: true
        },
        rowConfig:{keyField:'_X_ROW_KEY'},
        sortConfig: {
          trigger: 'cell',
          remote: true
        },
        filterConfig: {
          remote: true
        },
        pagerConfig: {
          pageSize: 20,
          pageSizes: [ 20, 50, 100, 200, 500, 1000]
        },
        formConfig: {
          titleWidth: 100,
          titleAlign: 'right',
          items: [
          ]
        },
        toolbarConfig: {
          buttons: [
            { code: 'insert_actived', name: '新增' },
            { code: 'delete', name: '删除' },
            { code: 'save', name: '保存', status: 'success' }
          ],
          refresh: true,
          custom: true,
          import: true,

        },
        proxyConfig: {
          seq: true, // 启用动态序号代理，每一页的序号会根据当前页数变化
          sort: true, // 启用排序代理，当点击排序时会自动触发 query 行为
          filter: true, // 启用筛选代理，当点击筛选时会自动触发 query 行为
          form: true, // 启用表单代理，当点击表单提交按钮时会自动触发 reload 行为
          // 对应响应结果 { result: [], page: { total: 100 } }
          props: {
            result: 'result', // 配置响应结果列表字段
            total: 'page.total' // 配置响应结果总页数字段
          },
          // 只接收Promise，具体实现自由发挥
          ajax: {
            // 当点击工具栏查询按钮或者手动提交指令 query或reload 时会被触发
            query: ({ page, sorts, filters, form }) => {

              return new Promise(resolve => {
                const queryParams = Object.assign(page,{searchField:state.queryForm})
                queryParams['pageNum']=queryParams.currentPage
                // // 处理排序条件
                // const firstSort = sorts[0]
                // if (firstSort) {
                //   queryParams.sort = firstSort.field
                //   queryParams.order = firstSort.order
                // }
                // // 处理筛选条件
                // filters.forEach(({ field, values }) => {
                //   queryParams[field] = values.join(',')
                // })
                listTemplate(state.templateCode, 0, queryParams).then(response => {
                  resolve({
                    result: response.data.list||[],
                    page: {
                      total: response.data.total
                    }
                  })
                })
              })
            },
            // 当点击工具栏删除按钮或者手动提交指令 delete 时会被触发
            delete: ({ body }) => {
              return new Promise(resolve => {
                delTemplate(state.templateCode, state.MainTable.tableName, XEUtils.pluck(body.removeRecords, 'RecordID')).then(response => {
                  resolve({})
                })
              })
            },
            // 当点击工具栏保存按钮或者手动提交指令 save 时会被触发
            save: ({ body }) => {
              console.log(body)
              return new Promise(resolve => {
                editsForm(state.templateCode, body.updateRecords.concat(body.insertRecords.map(row=>{delete row['_X_ROW_KEY'];return row}))).then((res) => {
                  resolve({})
                });
              })
            }
          }
        },
        columns: [
          { type: 'checkbox',  width: 60 },
          { type: 'seq', title: '#', width: 60 },
          { field: 'RecordID',title: 'RecordID',width: 100, visible:false }
        ],
        checkboxConfig: {
          labelField: 'id',
          reserve: true,
          highlight: true,
          range: true
        },
        editRules: {
        },
        editConfig: {
          trigger: 'manual',
          mode: 'row',
          showStatus: true
        },

        importConfig: {
          remote: true,
          types: ['xlsx'],
          modes: ['insert'],
          // 自定义服务端导入o
          importMethod ({ file }) {
            const $grid = xGrid.value
            const formBody = new FormData()
            formBody.append('upload-file', file)
         return   importTemplate(state.templateCode, formBody).then(res => {
              if (res.code === 0) {
                // this.msgError(res.msg)
                ElMessage({type: 'success',message: "文件导入成功"})
                $grid.commitProxy('query')
              }else {
                ElMessage({ message: '导入失败，请检查数据是否正确！', type: 'error' })
              }
            })
            // return fetch(`${serveApiUrl.value}/api/pub/import`, { method: 'POST', body: formBody }).then(response => response.json()).then(data => {
            //   VXETable.modal.message({ content: `成功导入 ${data.result.insertRows} 条记录！`, status: 'success' })
            //   // 导入完成，刷新表格
            //
            // }).catch(() => {
            //   VXETable.modal.message({ content: '导入失败，请检查数据是否正确！', status: 'error' })
            // })
          }
        },

      }
    })

    const formatData = ({ cellValue }) => {
      return cellValue
    }

    let EditData = ref(null)
    onBeforeMount(async () => {
      // if (state.load){
      //   return
      // }
      if (navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/webOS/i) || navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/BlackBerry/i) || navigator.userAgent.match(/Windows Phone/i)) {
        state.isequipment = false;
      } else {
        state.isequipment = true
      }
      if (route.params.id !== '0'){
        state.Add=false
      }
      state.templateCode =route.path.replace("/form/edits/",'')

        await getTemplate(state.templateCode).then( (response) => {
          state.MainTable = response.data.tables[0]
          // state.DetailTables = response.data.tables.filter(item => item.tableType === 1).map(row=>{
          //   row['Orders']=response.data.orders[row.tableName]
          //   row.TreeSum= {}
          //   if(row.layoutStyle.length>0){
          //     const tt=row.layoutStyle.split('|');
          //     row.layoutStyle=tt[0].split(',');
          //     if(tt.length>1)
          //     row.TreeSum=JSON.parse(tt[1]);
          //   } else{row.layoutStyle=[]}
          //   row.onSheet=row.onSheet.length>0?row.onSheet.split(','):[];
          //   return row
          // })
          state.ActRules = BuildRules(XEUtils.orderBy((XEUtils.toArray(response.data['actRules'] || []).filter(item => item.isActive === 1)), 'runSeq'))
          state.rules = response.data.editRules || []
          state.combo = response.data.combos
          state.Linker = response.data.linker
          state.Action = response.data.action
          state.Template = response.data.template
          XEUtils.arrayEach(response.data.tables, row => {
            state.Fields[row.tableName] = row.Fields.map(it=>{
              it.params=it
              return it

            })
          })
        })
      const ff = Object.assign([], state.Fields[state.MainTable.tableName])
      const items=[]
      const ffileds = ff.map(it => {
        const row = {
          field: it.fieldName,
          width: it.allowFixedWidth > 0 ? it.allowFixedWidth : 100,
          title: it.fieldDispName,
          // formatter: 'formatData',
          headerAlign: 'center', visible: it.hidden === 0,
          sortable: it.orderBy > 0,
          params: {column: it},
          showOverflow: it.showRichText !== 1,
          editRender: {autofocus: '.vxe-input--inner'},
          slots: {edit:'editForm',default:'defaultForm'}
        }

        if(it.fieldAreaName!==''){
          items.push(it)
        }
        return row
      })
      state.gridOptions.columns = state.gridOptions.columns.concat(ffileds).concat([{title:'操作',slots:{default:'operator'}}])
      if(items.length>0){
        state.queryFromShow=true
        //state.gridOptions.formConfig.items=state.gridOptions.formConfig.items.concat(items)
        state.querydfFields=state.querydfFields.concat(items)
      }

    })
    const showSource = async ({item, value, target, ref}) => {
      if (item.componentFilterExpr !== '' && item.componentType === 3) {
        if (state.filters[item.fieldName]===undefined){
          state.filters[item.fieldName]=XEUtils.clone(item.componentFilterExpr, true)
        }
        let filter = XEUtils.clone( state.filters[item.fieldName], true)
        const regex = /({(\S+)})/gis
        let m
        let keys = [], vals = []
        while ((m = regex.exec(filter)) !== null) {
          // 这对于避免零宽度匹配的无限循环是必要的
          if (m.index === regex.lastIndex) {
            regex.lastIndex++
          }
          // 结果可以通过`m变量`访问。
          m.forEach((match, groupIndex) => {
            if (groupIndex === 1) {
              keys.push(match)
            }
            if (groupIndex === 2) {
              vals.push(match)
            }
          })
        }
        XEUtils.arrayEach(keys, (it, key) => {
          //   // 主字段查找
          let val = XEUtils.get(state.formData, vals[key], '')
          if (val === '') {
            //     // 明细表行数据查找
            val = XEUtils.get(target, vals[key], '')
          }
          if (filter.indexOf(' in ') > 1) {
            const data = XEUtils.pluck(XEUtils.clone(state.itemRefs[ref].getTableData().fullData, true), vals[key])
            // console.log(data,'dddddd')
            let vv=data?data.join("','"):''
            filter = filter.replace(it, `'${vv}'`)
          }else{
            filter = filter.replace(it, val)
          }
        })

        item.componentFilterExpr = filter
      }
      DGE.value.Data = Object.assign({}, {field: item, value: value, data: state.formData})
      DGE.value.todo()
      DGE.value.keyword=''
      // this.$refs.DGE.showDialog = true
      state.selectDataGridTarget = {field: item, target: target, ref: ref}
    }

    const getextend = (data, field) => {
      let extend = XEUtils.toStringJSON(data['Extend'] ? data['Extend'] : '{}')
      if (extend[field.fieldName] === undefined) {
        extend[field.fieldName] = data[field.fieldName]
        data['Extend'] = XEUtils.toJSONString(extend)
      }
      return XEUtils.get(extend, field.fieldName)
    }
    const BuildRules = (data) => {
      const Rules = {}, rs = ["取数命令", '更新命令', '传送命令']
      XEUtils.arrayEach(data, row => {
        if (Rules[rs[row.ruleType - 1]] === undefined) {
          Rules[rs[row.ruleType - 1]] = []
        }
        Rules[rs[row.ruleType - 1]].push(row)
      })
      return Rules
    }
    const ValueChange = async (data, fields, fieldName, tableName) => {
      let source = XEUtils.clone(data, true)
      let extend = XEUtils.toStringJSON(data['Extend'])
      source = XEUtils.objectMap(source, item => item === null ? 0 : item)
      XEUtils.objectEach(fields, async (field) => {
        if (field.componentType === 9 && field.componentFieldName !== ''&& field.fieldName!==fieldName) {
          const jgm = mathAll(field.componentFieldName, source)
          data[field.fieldName] = jgm ? XEUtils.round(jgm, field.fieldPrecision) : jgm
        }
        if (field.dataTypeID !== 6 && field.componentType === 0 && extend[field.fieldName] !== null && extend[field.fieldName] !== undefined) {
          extend[field.fieldName] = data[field.fieldName]
        }
      })
      data['Extend'] = JSON.stringify(extend)
    }
    const dfQuery = () => {
      fastSearch.value = '1=1 '
      const FF=[]
      XEUtils.objectEach(XEUtils.pick(state.queryForm, val => !XEUtils.isEmpty(val)), (item, key) => {
        const field=state.querydfFields.find(item=>item.fieldName===key)
        if (field){
          if(field.fieldAreaName==='like'){
            FF.push(XEUtils.template(" {{field}} like '%{{name}}%' ", {name: item,field:key}))
          }else if(field.fieldAreaName==='between'){
            FF.push(XEUtils.template(" {{field}} between '{{name[0]}}' and '{{name[1]}}' ", {name: item.split(","),field:key}))
          }else if(field.fieldAreaName==='in'){
            FF.push(XEUtils.template(" {{field}} in ({{name}}) ", {name: item,field:key}))
          }else{
            FF.push(XEUtils.template(" {{field}} {{query}} '{{name}}' ", {query:field.fieldAreaName,name: item,field:key}))
          }
        }else {
          FF.push( ` ${key} like '%${item}%' `)
        }
      })
      fastSearch.value= FF.length>0?fastSearch.value+' and '+FF.join('and'):fastSearch.value
      state.selectMainData = null
        xGrid.value.commitProxy('query')


    }
    const getSourceData = ({data, data2, C}) => {
      const field = JSON.parse(state.selectDataGridTarget.field.componentFieldName)
      const target = state.selectDataGridTarget.target
      const keys = state.selectDataGridTarget.ref

      let isBT = true
      if (XEUtils.has(target, 'Seq')) {
        isBT = false
      }
      const tb = XEUtils.find(props.DT, item => MainTable.tableName === keys)
      if (isBT) {
        XEUtils.objectEach(field, (item, key) => {
          target[key] = XEUtils.pluck(data, item.v).join(",")
          let extend = XEUtils.toStringJSON(target['Extend'])
          const F = state.Fields[keys].find(item => item.fieldName === key)
          if (F!==undefined && F['componentType'] === 3) {
            extend[key] = XEUtils.pluck(data, item.v).join(",")
          }
          target['Extend'] = XEUtils.toJSONString(extend)
        })
      } else {
        data.forEach(async (row, index) => {

          const newrow = await getDTdefault(keys)
          if (tb.layoutStyle.length > 0) {
            newrow[tb.layoutStyle[1]] = state.parentV
          }
          XEUtils.objectEach(field, (item, key) => {
            // 对象迭代器，只能用于遍历对象，性能高于 each
            if (row[item.v]) {
              newrow[key] = row[item.v]
            }

            let extend = XEUtils.toStringJSON(newrow['Extend'])
            const F = state.Fields[keys].find(item => item.fieldName === key)
            if (F!==undefined &&F['componentType'] === 3) {
              extend[key] = data[index][item.v]
            }
            newrow['Extend'] = XEUtils.toJSONString(extend)
          })

          XEUtils.objectEach(state.Fields[keys], (item, key) => {
            if (item.componentType === 9 && item.componentFieldName !== '') {
              const jgm = mathAll(item.componentFieldName, newrow)
              newrow[item.fieldName] = jgm ? XEUtils.toFixed(jgm, item.fieldPrecision) : jgm
            }
          })
          if (tb.layoutStyle.length>0&&newrow[tb.layoutStyle[0]] === newrow[tb.layoutStyle[1]]) {
            return false
          }
          if (index === 0) {
            XEUtils.objectEach(newrow, (item, key) => {
              if (item) {
                target[key] = item
              }
            })
          } else {
            const $tb = state.itemRefs[keys]
            $tb.insertAt(newrow, -1)

          }
        })
      }
      ValueChange(target, state.Fields[keys], state.selectDataGridTarget.field.fieldName,keys)
    }
    const editRowEvent = (row) => {
      const $grid = xGrid.value
      if ($grid) {
        $grid.setEditRow(row)
      }
    }
    const cancelRowEvent = (row) => {
      const $table = xGrid.value
      $table.clearEdit().then(() => {
        // 还原行数据
        $table.revertData(row)
      })
    }
    const saveRowEvent = async () => {
      const $grid = xGrid.value
      if ($grid) {
        await $grid.clearEdit()
        // state.gridOptions.loading = true
        // // 模拟异步保存
        // setTimeout(() => {
        //   state.gridOptions.loading = false
        //   VXETable.modal.message({ content: '保存成功！', status: 'success' })
        // }, 300)
      }
    }

    const removeRowEvent = async (row) => {
      const type = await VXETable.modal.confirm('您确定要删除该数据?')
      const $grid = xGrid.value
      if ($grid) {
        if (type === 'confirm') {
          await $grid.remove(row)
        }
      }
    }
    return {
      EditData,xGrid,fastSearch,DGE,Plus,
      ...toRefs(state)
      , getextend,ValueChange,dfQuery,formatData,showSource,getSourceData
      , BuildRules,editRowEvent,saveRowEvent,removeRowEvent,cancelRowEvent

    }
  }
}
</script>

<style scoped>
.p-10 {
  padding: 10px;
  background-color: rgb(255, 255, 255);
}

</style>